//
//  Contacts.m
//  Truffle
//
//  Created by Fabrice Troilo on 10/02/10.
//  Copyright 2010 DQS. All rights reserved.
//
//  Cette page gère l'affichage graphique des contacts dans l'application
//  Connexion REST + JSON faites à chaque lancement de la page pour récupérer :
//  * les contacts connectés à la passerelle de référence
//  * les contacts favoris demandés à la passerelle de référence, qui peuvent être sur n'importe quelle passerelle
//     en envoyant en GET les identifiant
//

#import "Clients.h"
#import "Carte.h"
#import "RestConnection.h"
#import "DatasTruffle.h"
#import "Contact.h"
#import "DAOTruffle.h"
#import "Gateway.h"

@interface Clients(private)

- (void)requestContacts;
- (void)requestFavorites;
- (void)refreshAction;

@end

// voir si la vue n'a pas encore été chargée
BOOL firstViewc = TRUE;
// permet de savoir si la requète rest est finie.
BOOL finishRest = FALSE;
// cette variable permet de savoir si la première requête a été faite
BOOL firstRequest = FALSE;
// les passerelles connectées
NSMutableArray *passerelles;

@implementation Clients

@synthesize label, tableView;

- (void)dealloc {
	[carte release];
	[hashListConnected release];
	[hashListFavorites release];
    [super dealloc];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	[disconnectedImageView removeFromSuperview];
	[activityIndicator setHidesWhenStopped:TRUE];
	if(![DatasTruffle isConnected]) {
		[tableView addSubview:disconnectedImageView];
		disconnectedImageView.alpha=0.0;
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:2.0];
		disconnectedImageView.alpha=0.8;
		[UIView commitAnimations];
		[activityIndicator stopAnimating];
	} else {
		
		passerelles = [DatasTruffle getGateways];
		
		/*
		 * TODO
		 * Syntaxe définie avec Rachid Habel (team 2)
		 * restConnection.baseURLString = [[passerelles objectAtIndex:0] objectForKey:@"reference"];
		 */
		
		/**** Debut REST ****/
		/*restConnection = [RestConnection new];
		restConnection.baseURLString = @"http://www.kidikoa.fr/";
		restConnection.delegate = self;*/
		if(passerelles != nil ) {
			if([[passerelles objectAtIndex:0] name]!=nil && ![[[passerelles objectAtIndex:0] name] isEqualToString:@"null"]) {
				
				NSLog(@">> [Clients.m] Connexion à l'annuaire OK");
				restConnection = [RestConnection new];
				restConnection.baseURLString = [[passerelles objectAtIndex:0] ip];
				restConnection.delegate = self;
				[self requestContacts];	
				
			} else {
				
				NSLog(@">> [Clients.m] Problème de récupération des passerelles à l'annuaire");
				[tableView addSubview:disconnectedImageView];
				disconnectedImageView.alpha=0.0;
				[UIView beginAnimations:nil context:NULL];
				[UIView setAnimationDuration:2.0];
				disconnectedImageView.alpha=0.8;
				[UIView commitAnimations];
				[activityIndicator stopAnimating];
				
			}

		} else {
			NSLog(@">> [Clients.m] Problème de récupération des passerelles à l'annuaire");
		}

		/**** FIN REST ****/
	}
	
	hashListConnected=[[NSMutableDictionary alloc] init];
	hashListFavorites=[[NSMutableDictionary alloc] init];
	
	UIBarButtonItem *reloadButton = [[UIBarButtonItem alloc] 
									 initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh   
									 target:self 
									 action:@selector(refreshAction)];
	
	[self.navigationItem setLeftBarButtonItem:reloadButton];
	self.navigationItem.leftBarButtonItem.enabled = YES;
	
	//Création du segmentedControl pour voir Tous / favoris
	segmentedControl = [ [ UISegmentedControl alloc ] initWithItems: nil ]; 
	segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; 
	//ajout des titles
	[ segmentedControl insertSegmentWithTitle: @"Tous" atIndex: 0 
									 animated: NO 
	 ]; 
	[ segmentedControl insertSegmentWithTitle: @"Favoris" atIndex: 1 
									 animated: NO 
	 ]; 
	//ajout de la fonction et target
	[segmentedControl addTarget: self action: @selector(controlPressed:) forControlEvents:UIControlEventValueChanged]; 
	//ajout du bouton au navigation item        
	self.navigationItem.titleView = segmentedControl; 
	self.navigationItem.titleView.hidden=YES;
	//de base le selector est sur tous
	segmentedControl.selectedSegmentIndex = 0; 
	self.navigationItem.rightBarButtonItem.enabled = NO;
}

//the controlPressed action method
- (void)controlPressed:(id) sender { 
    [self setPage]; 
} 

//the set page method sets the testViewText
- (void)setPage { 
    int index = segmentedControl.selectedSegmentIndex;
	
    if (index == 0) { 
		[tableView reloadData];
		self.navigationItem.rightBarButtonItem = nil;
    } else { 
		[self.tableView setEditing:NO animated:NO];
		[tableView reloadData];
		[self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(turnOnEditing)]];
		self.navigationItem.rightBarButtonItem.enabled = YES;
	}
} 

/*
 * Le titre de chaque header de section de tableau
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	// Si on est pas connecté
	if(![DatasTruffle isConnected]) {
		return @"";
	}

	// Si on est connecté
	if (segmentedControl.selectedSegmentIndex == 0) {
        switch (section) {
			case(0): {
				/*
				 * TODO
				 * syntaxe définie avec Rachid Habel (Team 2)
				 * NSString * namePass = [[passerelles objectAtIndex:0] objectForKey:@"position"];
				 */
				NSString * namePass = [[passerelles objectAtIndex:0] name];
				if (namePass != nil) {
					return [NSString stringWithFormat:@"Connectés à %@",namePass];
				} else {
					return [NSString stringWithFormat:@"Aucune connexion"];
				}
				[namePass release];
				break;
			}
			default :
				break;
		}
    } else if (segmentedControl.selectedSegmentIndex == 1) {
		switch (section) {
			case(0): {
				return @"Favoris";
				break;
			}
			default :
				break;
		}
    }
	return nil;
}


/*
 * Rechargement de la page lors de l'apparition de la vue
 */
- (void)viewWillAppear:(BOOL)animated {
	//dao = [[DAOTruffle alloc] init];
	if(firstViewc) {
		firstViewc=FALSE;
	} else {
		[self refreshAction];
	}
}

/* 
 * Nombre de sections (1)
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tblView {
	return 1;
}


/* 
 * Nombre de cellules dans chaque section
 */
- (NSInteger)tableView:(UITableView *)tblView numberOfRowsInSection:(NSInteger)section {
	if (segmentedControl.selectedSegmentIndex == 0) { 
        switch (section) {
			case(0): {
				return [hashListConnected count];
				break;
			}
			default :
				break;
		}
    } else if (segmentedControl.selectedSegmentIndex == 1) {
		switch (section) {
			case(0): {
				return [hashListFavorites count];
				break;
			}
			default :
				break;
		}
    }
	return -1;
}

// Pour mettre la fleche sur la cellule par defaut sans en faire un bouton !!!
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	return UITableViewCellAccessoryDisclosureIndicator;
}

- (UITableViewCell *)tableView:(UITableView *)tblView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	static NSString *CellIdentifier = @"Contacts";
	//faire un identifier cellFav
	UILabel * typeRef;
	
	UITableViewCell *cell = [tblView dequeueReusableCellWithIdentifier:CellIdentifier];

	cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
	
	int nbviews = [[cell subviews] count];
	UIFont *displayFont = [UIFont boldSystemFontOfSize:14];
	
	[cell addSubview:[[UILabel alloc] initWithFrame:CGRectMake(60.0f, 13.0f, 150.0f, 20.0f)]];
	typeRef = [[cell subviews] objectAtIndex:nbviews];
	NSString * libelle;
	
	//UIButton pour ajouter en favoris
	UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
	[button setFrame:CGRectMake(15.0f, 8.0f, 30.0f, 30.0f)];
		
	//image non visible pense a les ajouter
	UIImage *image=[UIImage imageNamed:@"favori.png"];
	UIImage *imageb=[UIImage imageNamed:@"favorib.png"];
	
	/*
	 * CLLocation *hisLocation = [[CLLocation alloc] initWithLatitude:+37.48873634f longitude:-121.97420502f];
	 * CLLocation *myLocation = [[CLLocation alloc] initWithLatitude:+37.49873734f longitude:-121.97420502f];
	 * CLLocationDistance distance =[hisLocation getDistanceFrom:myLocation];
	 * NSString *sDistance=[NSString stringWithFormat:@" (%.lf" , floor(fabs(distance))];
	 * sDistance=[sDistance stringByAppendingString:@" m)"];
	 */
	
	typeRef.font = displayFont;
	int idx = indexPath.row;
	
	//switch sur les sections du UITableView
	if (segmentedControl.selectedSegmentIndex == 0) { 
        switch (indexPath.section) {
			case(0): {
				libelle = [[hashListConnected objectForKey:[NSString stringWithFormat:@"%d",idx]] pseudo];
				typeRef.text = libelle;
				typeRef.highlightedTextColor =  [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];

				if(![[DatasTruffle getDao] isFavori:[hashListConnected objectForKey:[NSString stringWithFormat:@"%d",idx]]]) {
					[button setBackgroundImage:imageb forState:UIControlStateNormal];
					[button setBackgroundImage:imageb forState:UIControlStateHighlighted];
					button.tag=idx;
					[button addTarget:self action:@selector(ajoutFavori:) forControlEvents:UIControlEventTouchUpInside];
				} else {
					[button setBackgroundImage:image forState:UIControlStateNormal];
					[button setBackgroundImage:image forState:UIControlStateHighlighted];
				}
				[cell addSubview:button];
				
				break;
			}
			default :
				break;
		}
    } else if (segmentedControl.selectedSegmentIndex == 1) {
		switch (indexPath.section) {
			case(0): {
				//NSLog(@"PSEUDO : %d %@",idx, [[hashListFavorites objectForKey:[NSString stringWithFormat:@"%d",idx]] pseudo]);
				libelle=[[hashListFavorites objectForKey:[NSString stringWithFormat:@"%d",idx]] pseudo];
				typeRef.text = libelle;
				typeRef.highlightedTextColor =  [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
				[button setBackgroundImage:image forState:UIControlStateNormal];
				[button setBackgroundImage:image forState:UIControlStateHighlighted];
				[cell addSubview:button];
				break;
			}
			default :
				break;
		}
    }
	return cell;
}

/* 
 * Sauvegarde un contact dans la BD 
 */
- (void)ajoutFavori:(id)sender {
	
	int myTag = [sender tag];
	
	Contact *contact = [hashListConnected objectForKey:[NSString stringWithFormat:@"%d", myTag]];
	[[DatasTruffle getDao] addContact:contact];
	[hashListFavorites setObject:[hashListConnected objectForKey:[NSString stringWithFormat:@"%d", myTag]] forKey:[NSString stringWithFormat:@"%d",[hashListFavorites count]]];
	
	[contact release];
	[tableView reloadData];
}

/*
 * Lors de la sélection d'une cellule de table
 * Affichage de la carte de la position du client
 */
- (void)tableView:(UITableView *)tblView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	carte = [[Carte alloc] initWithNibName:@"Carte" bundle:nil];
	
	if (segmentedControl.selectedSegmentIndex == 0) {
		Contact * contact = [hashListConnected objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];
		[carte setLatitude:[contact.latitude floatValue]];
		[carte setLongitude:[contact.longitude floatValue]];
		[carte setPseudo:[[hashListConnected objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]] pseudo]];
		[contact release];
	} else {
		Contact * contact = [hashListFavorites objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]];
		[carte setLatitude:[contact.latitude floatValue]];
		[carte setLongitude:[contact.longitude floatValue]];
		[carte setPseudo:[[hashListFavorites objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]] pseudo]];
		[contact release];
	}
		
	[self.navigationController pushViewController:carte animated:YES];
	[carte release];
	[tableView reloadData];
}



/*
 * Editing sur la table view pour les favoris
 */
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
	
		[[DatasTruffle getDao] removeContact:[hashListFavorites objectForKey:[NSString stringWithFormat:@"%d",indexPath.row]]];
		
		for (int i=indexPath.row;i<[hashListFavorites count]-1;i++){
			[hashListFavorites setObject:[hashListFavorites objectForKey:[NSString stringWithFormat:@"%d",i+1]] forKey:[NSString stringWithFormat:@"%d",i]];
		}
		
		[hashListFavorites removeObjectForKey:[NSString stringWithFormat:@"%d",[hashListFavorites count]-1]];
		[self.tableView reloadData];
	} 
}


- (void)setEditing:(BOOL)editing animated:(BOOL)animated { 
	[super setEditing:editing animated:animated];
	[self.tableView setEditing:editing animated:YES];
} 


/*
 * Savoir sur quel table on peut éditer
 */
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
	if (segmentedControl.selectedSegmentIndex == 0) { 
        switch (indexPath.section) {
			case(0): {
				return NO;
				break;
			}
			default :
				break;
		}
    } else if (segmentedControl.selectedSegmentIndex == 1) {
		switch (indexPath.section) {
			case(0): {
				return YES;
				break;
			}
			default :
				break;
		}
    }
	
	return NO;
}

- (void)edit:(id)sender
{
    [self.tableView setEditing:YES animated:YES];
}

- (void)cancel:(id)sender
{	
    [self.tableView setEditing:NO animated:YES];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

#pragma mark RestConnectionDelegate

- (void)willSendRequest:(NSURLRequest *)request
{
	[activityIndicator startAnimating];
}

- (void)didReceiveResponse:(NSURLResponse *)response
{
	//NSLog(@"didReceiveResponse: %@", response);
}

- (void)finishedReceivingData:(NSData *)data callback:(NSString*)restconn
{
	
	/* récupération des contacts connectés*/
	if(!firstRequest) {
		
		NSLog(@">> [Clients.m] Connectés reçus : %@", [restConnection stringData]);
		
		// Get the dictionary containing the raw parsed data.
		NSDictionary *rawData = [restConnection dictionaryData];
	
		//NSLog(@"RAWDATA : %@", rawData);
		
		[tableData release];
		
		/*
		 * TODO
		 * Syntaxe définie avec Rachid Habel (team 2)
		 * tableData = [[rawData objectForKey:@"listclient"] retain];
		 */
		tableData = [[rawData objectForKey:@"listclient"] retain];
		
		for(int cpt=0;cpt<[tableData count];cpt++) {
			/* 
			 * TODO
			 * [hashListAmis1 setObject:[NSString stringWithFormat: @"%@",[[tableData objectAtIndex:cpt] objectForKey:@"pseudo"]] 
			 forKey:[NSString stringWithFormat: @"%@",[[tableData objectAtIndex:cpt] objectForKey:@"id"]]];
			 */
			Contact * contact = [[Contact alloc] initContactWithLatLong:[NSString stringWithFormat: @"%@",[[tableData objectAtIndex:cpt] objectForKey:@"id"]] 
														:[NSString stringWithFormat: @"%@",[[tableData objectAtIndex:cpt] objectForKey:@"pseudo"]]
														:[NSString stringWithFormat: @"%@",[[tableData objectAtIndex:cpt] objectForKey:@"latitude"]]
														:[NSString stringWithFormat: @"%@",[[tableData objectAtIndex:cpt] objectForKey:@"longitude"]]];
		
			[hashListConnected setObject:contact forKey:[NSString stringWithFormat:@"%d",cpt]];
			[tableView reloadData];
		}
		
	
		[self requestFavorites];
		
		firstRequest=TRUE;
		
	/* récupération des contacts favoris*/
	} else {
		NSLog(@">> [Clients.m] Favoris reçus : %@", [restConnection stringData]);
		// Get the dictionary containing the raw parsed data.
		NSDictionary *rawData = [restConnection dictionaryData];
		
		[tableDataFav release];
		/*
		 * TODO
		 * Syntaxe définie avec Rachid Habel (team 2)
		 * tableData = [[rawData objectForKey:@"listclient"] retain];
		 */
		tableDataFav = [[rawData objectForKey:@"listclient"] retain];
		//[rawData release];
		
		for(int cpt=0;cpt<[tableDataFav count];cpt++) {
			/* 
			 * TODO
			 * [hashListAmis1 setObject:[NSString stringWithFormat: @"%@",[[tableData objectAtIndex:cpt] objectForKey:@"pseudo"]] 
			 forKey:[NSString stringWithFormat: @"%@",[[tableData objectAtIndex:cpt] objectForKey:@"id"]]];
			 */
			Contact * contact = [[Contact alloc] initContactWithLatLong:[NSString stringWithFormat: @"%@",[[tableDataFav objectAtIndex:cpt] objectForKey:@"id"]] 
																	   :[NSString stringWithFormat: @"%@",[[tableDataFav objectAtIndex:cpt] objectForKey:@"pseudo"]]
																	   :[NSString stringWithFormat: @"%@",[[tableDataFav objectAtIndex:cpt] objectForKey:@"latitude"]]
																	   :[NSString stringWithFormat: @"%@",[[tableDataFav objectAtIndex:cpt] objectForKey:@"longitude"]]];
			
			[hashListFavorites setObject:contact forKey:[NSString stringWithFormat:@"%d",cpt]];
			[tableView reloadData];
		}
		
		NSLog(@">> Amis favoris reçus");
		
		[activityIndicator stopAnimating];
		
		self.navigationItem.titleView.hidden=NO;
		firstRequest=FALSE;
	}
}


#pragma mark Private Methods

/* 
 * requète rest pour récupérer les contacts connectés
 */
- (void)requestContacts
{	
	/*
	 * TODO
	 * Syntaxe définie avec Rachid Habel (team 2)
	 * NSString *urlString = @"/iphone/listconnected";
	 */
	NSString *urlString = @"/iphone/listconnected";
	[restConnection performRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
	NSLog(@">> url requête contacts : %@",urlString);
}

/* 
 * requète rest pour récupérer les contacts favoris
 */
- (void)requestFavorites
{	
	/*
	 * TODO
	 * Syntaxe définie avec Rachid Habel (team 2)
	 * NSString *urlString = @"/iphone/friends";
	 */
	NSString *urlString = @"/iphone/friends";
	NSString *requestString =[NSString stringWithFormat:@"%@/iphone/friends/", [[passerelles objectAtIndex:0] ip]];
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]
														   cachePolicy:NSURLRequestUseProtocolCachePolicy
													   timeoutInterval:15.0];
	[request setURL:[NSURL URLWithString:requestString]];
	[request setHTTPMethod:@"POST"];
	
	//DAOTruffle *dao = [[DAOTruffle alloc] init];
	NSMutableArray *favBd = [[DatasTruffle getDao] getContacts];
	//[dao release];
	NSString *post = @"";
	for(int cpt=0;cpt<[favBd count];cpt++) {
		//NSLog(@"%@&id=%@",post, [[favBd objectAtIndex:cpt] UUID]);
		post = [NSString stringWithFormat:@"%@&id=%@",post, [[favBd objectAtIndex:cpt] UUID]];
	}
	
	[favBd release];
	
	NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
	[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:postData];
	
	[restConnection performRequest:request];
}

- (void)turnOnEditing {
	[self.navigationItem.rightBarButtonItem release];
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(turnOffEditing)];
	[self.tableView setEditing:YES animated:YES];
}

- (void)turnOffEditing {
	[self.navigationItem.rightBarButtonItem release];
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(turnOnEditing)];
	[self.tableView setEditing:NO animated:YES];
}

/*Refresh de la page */
- (void)refreshAction {
	[super viewDidLoad];
	
	[activityIndicator startAnimating];
	
	[hashListConnected release];
	hashListConnected = [[NSMutableDictionary alloc] init];
	[hashListFavorites release];
	hashListFavorites = [[NSMutableDictionary alloc] init];
	
	if(![DatasTruffle isConnected]) {
		[tableView addSubview:disconnectedImageView];
		disconnectedImageView.alpha=0.0;
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:2.0];
		disconnectedImageView.alpha=0.8;
		[UIView commitAnimations];
		[activityIndicator stopAnimating];
		
	} else {
		//getTableData
		passerelles = [DatasTruffle getGateways];
		
		/*
		 * TODO
		 * Syntaxe définie avec Rachid Habel (team 2)
		 * restConnection.baseURLString = [[passerelles objectAtIndex:0] objectForKey:@"reference"];
		 */
		
		/**** Debut REST ****/
		/* restConnection = [RestConnection new];
		 * restConnection.baseURLString = @"http://www.kidikoa.fr/";
		 * restConnection.delegate = self;
		/**** FIN REST ****/
		if(passerelles != nil ) {
			if([[passerelles objectAtIndex:0] name]!=nil && ![[[passerelles objectAtIndex:0] name] isEqualToString:@"null"]) {
				
				NSLog(@">> Connexion à l'annuaire OK");
				restConnection = [RestConnection new];
				restConnection.baseURLString = [[passerelles objectAtIndex:0] ip];
				restConnection.delegate = self;
				
				[self requestContacts];	
				
			} else {
				NSLog(@">> Problème de récupération des passerelles à l'annuaire");
				[tableView addSubview:disconnectedImageView];
				disconnectedImageView.alpha=0.0;
				[UIView beginAnimations:nil context:NULL];
				[UIView setAnimationDuration:2.0];
				disconnectedImageView.alpha=0.8;
				[UIView commitAnimations];
				[activityIndicator stopAnimating];
				
			}
			
		} else {
			NSLog(@">> Problème de récupération des passerelles à l'annuaire");
		}
	}
	
}

@end
